<template>
	<view class="wrap">
		<js-error mode="bottom" ref="jsError" @update:errorcClose="onErrorClose"></js-error>
		<view class="cu-bar search" style="padding: 10px" ref="cu-bar">
			<u-search v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描机台" :show-action="false"
				@search="confirmSearch" height="74"></u-search>
			<view style="margin-left: 10px; display: flex; flex-direction: column">
				<u-icon @click="search" name="scan" size="60"></u-icon>
			</view>
		</view>
		<view class="cu-bar search" style="padding: 10px" ref="cuBar" v-if="lineCode">
			<u-form style="width: 100%;">
				<u-form-item label="机台" prop="id" label-width="180" style="font-weight: 800;">
					<view>{{ lineCode || ' '}}</view>
				</u-form-item>
			</u-form>
		</view>

		<view v-show="currentRW ">
			<scroll-view
			  scroll-y="true"
			  :style="{ height: computedScrollViewHeight }"
			  
			>
			<!-- style="margin: 20px 0" -->
				<view class="margin-sm">
					<u-section
					  title="当前机台正在加工任务"
					  :right="false"
					  line-color="blue"
					  font-size="30"
					  v-if="list.length>0"
					></u-section>
					<view class="wrap" v-if="list.length>0">
						<u-form class="form" ref="uForm" label-position="left" :model="model" :rules="rules" v-for="(item,index) in list" :key="item.id">
							<u-form-item label="" prop="id" label-width="180" style="font-weight: 800;">
								<template>
									<view class="flex title">
										<view style=" display: inline-block;background: #3E97B0;color: #fff;width: 30px;text-align: center;font-style: italic;font-weight: bold;margin-right: 5px	;">
															{{ index + 1 }}
										</view>
									</view>
									<view class="flex align-center justify-end flex-sub">
										<view class="flex align-center">			
											<dictLabel
											v-if="!item.isDelFlag"
											:value="item.taskStatus ? item.taskStatus : ''"
											dict-type="mes_task_status"
											:dict-list="dictList"
											:fontSize="'30rpx'"
											></dictLabel>
											<text class="cuIcon-deletefill padding text-sl text-red" @tap="DelItem(item)" v-if="!!item.isDelFlag"></text>
										</view>
										
									</view>
								</template>
							</u-form-item>
							<u-form-item label="" prop="operator" style="font-weight: 800;">
								<template>
									<view class="flex title"><view>订单号</view></view>
									<view class="flex align-center justify-between flex-sub">
										<view>{{ item.scOrder ? item.scOrder.code || '' : ''}}{{item.scOrder ? item.scOrder.sortNum ? '#' + item.scOrder.sortNum : '' : ''}}</view>
									</view>
								</template>
							</u-form-item>
							<u-form-item label="操作工" prop="operator" label-width="180" style="color: red;font-weight: 800;" :required="true">
								<view class="flex"><u-input placeholder="请扫码" v-model="item.operator" type="text" maxlength="64" :custom-style="customStyle" disabled></u-input>
									  <text class="cuIcon-roundclose" @tap="clearOperator" v-if="item.operator&&!showFlag"></text>
									  
								</view>
							</u-form-item>
							<!-- <u-form-item label="班长" prop="monitor" label-width="180" style="color: red;font-weight: 800;" :required="true" v-if="item.showOperation">
								<view class="flex">
									<u-search v-model="barCodeGP" ref="uSearchGP" :focus="focusGP" placeholder="请先聚焦后扫描班长工牌" :show-action="false"	@search="confirmSearchGP" height="70" bg-color="none"> </u-search>
									<view style="margin-left: 10px; display: flex; flex-direction: column">
										<u-icon @click="searchGP" name="scan" size="60"></u-icon>
									</view>
								</view>
							</u-form-item> -->
							<!-- <u-form-item label="订单号" prop="id" label-width="180" >
								<view>{{ item.scOrder.code || ''}}{{item.scOrder.sortNum ? '#' + item.scOrder.sortNum : ''}}</view>
							</u-form-item> -->
							<u-form-item label="工序名称" prop="id" label-width="180">
								<view>{{ item.basOper.name || ''}}{{ item.basOper&&item.basOper.code ? '('+item.basOper.code+')' : ''}}</view>
							</u-form-item>
							<u-form-item label="存货编码" prop="id" label-width="180">
								<view>{{ item.basInv.cinvcode || ''}}</view>
							</u-form-item>
							<u-form-item label="存货名称" prop="id" label-width="180">
								<view>{{ item.basInv.cinvname || ''}}</view>
							</u-form-item>
							<u-form-item label="规格型号" prop="id" label-width="180">
								<view>{{ item.basInv.cinvstd || ''}}</view>
							</u-form-item>
							<u-form-item label="被分派人" prop="userNames" label-width="180">
								<view>{{ item.userNames || ''}}</view>
							</u-form-item>
							
							
						</u-form>
					</view>
					<view v-if="list.length==0">
						<u-empty :style="{height: emptyViewHeight+'px'}">
							<template #bottom>
								<view>当前机台暂无执行任务</view>
							</template>
						</u-empty>
					</view>
					
				</view>
				
			</scroll-view>
			<view class="btn-group cu-bar foot padding" ref="btn-group" v-if="!showFlag">
				<!-- round -->
				<button class="cu-btn  bg-confirm lg margin-left " @click="confirm" v-if="list.length>0">上机</button>	
					<button class="cu-btn  lines-red lg " @click="selectSJ">选择上机任务</button>
			</view>
		</view>
		
		<u-empty v-if="!currentRW" :style="{height: emptyViewHeight+'px'}"></u-empty>
		<custom-modal ref="customModal" v-if="showModal" :initial-message="modalMessage" @update:close="onModalClose" ></custom-modal>
	</view>
</template>

<script>
	import CustomModal from "@/pages/mes/components/CustomModal.vue";
	import dictLabel from "@/pages/mes/components/dictLabel.vue";
	export default {
		components: {
			CustomModal,
			dictLabel
		},
		data() {
			return {
				focus:true,
				focusGP:false,
				barCode:'',
				barCodeGP : '',
				model: {
					iqty:0,
					operator:''
				},
				rules: {
					operator: [
						{
							required: true,
							message: '请扫码操作工',
							trigger: ['change','blur'],
						}
					]
				},
				customStyle:{
					color:'red'
				},
				showModal: false,
				scrollViewHeight: 0,
				currentRW:false,
				emptyViewHeight:0,
				list:[],
				modid:'',
				lineCode:'',
				dictList:[],
				operatorNames:{},
				showFlag:false,
			}
		},
		onShow() {
			// 在onShow中监听事件
			uni.$once('selectedItems', (selectedItems) => {
				// 去重
				const uniqueSelectedItems = Array.from(new Set(selectedItems.map(item => item.id)));
				// 从this.list中过滤出不在uniqueSelectedItems中的项
				const filteredList = this.list.filter(item => !uniqueSelectedItems.includes(item.id));
				// 合并并去重
				this.list = [...filteredList, ...selectedItems].filter(
					(item, index, self) => self.findIndex(i => i.id === item.id) === index
				);
				// 遍历加一个显示操作工的标识
				// this.list.forEach(item => {
				// 	item.showOperation = true;
				// });
				this.focus = false;
				setTimeout(() => {
					this.barCode = ''
					this.focus = true;
				}, 500);
				console.log(this.list, 'merged and deduplicated list');
			});
			this.getDictList()
		},
		onLoad() {
			this.$nextTick(() => {
				this.calculateScrollViewHeight()
				this.emptyHeight()
			})
		},
		computed: {
		  computedScrollViewHeight() {
		    return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
		  },
		},
		onUnload(){
			uni.$off('selectedItems');
		},
		methods:{
			clearOperator(){
				this.showCustomModal("确定要删除操作工").then((res) => {
					if(res){
						this.list[0]['operator'] = ''
						this.operatorNames = {}
						this.$forceUpdate()
					}
				})
			},
			getDictList() {
				this.$u.api
					.dictListData({ dictType: "mes_task_status" })
					.then((res) => {
					this.dictList = res;
				});		
			},
			DelItem(item) {
				this.showCustomModal("确定删除吗？").then((res) => {
					if(res){
						const index = this.list.findIndex((element) => element.id === item.id); // 假设每个item有一个唯一的id属性
						if (index !== -1) {
							// 从数组中移除找到的项
							this.list.splice(index, 1);
						}
					}
				})
			},
			async calculateScrollViewHeight() {
			  try {
			// 等待头部高度计算完成
			      console.log(this.$refs,'this.$refs')
			      // 计算btn-group 高度
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const btnOffsetHeight = this.$refs['btn-group'] ? this.$refs['btn-group'].$el ? this.$refs['btn-group'].$el.offsetHeight : 0 : 0;
				  const cuBarOffsetHeight = this.$refs['cu-bar'] ? this.$refs['cu-bar'].$el ? this.$refs['cu-bar'].$el.offsetHeight : 109 : 0 ;
			      // 计算scroll-view高度
			      this.scrollViewHeight = screenHeight - ( btnOffsetHeight + cuBarOffsetHeight + 80 );
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			async emptyHeight() {
			  try {
				  // 等待头部高度计算完成
			      // 计算btn-group 高度
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const cuBarOffsetHeight = this.$refs['cu-bar'] ? this.$refs['cu-bar'].$el ? this.$refs['cu-bar'].$el.offsetHeight : 109 : 0;
			      // 计算scroll-view高度
			      this.emptyViewHeight = screenHeight - cuBarOffsetHeight;
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			confirmSearch(){	
				this.focus = false
				this.commonSearch(this.barCode)			
			},
			search(){
				var _that = this;
				_that.focus = false
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: async (res) => {
						_that.barCode = res.result;
						await _that.commonSearch(res.result)
					},
				});
			},
			async commonSearch(barCode){				
				let JT = this.vuex_config.JT;
				let GP = this.vuex_config.GP;
				console.log(this.barCode.indexOf(JT),'JT',this.barCode,JT,this.barCode.indexOf(GP))
				if (barCode.indexOf(JT) == -1 && barCode.indexOf(GP) == -1) {
					this.$refs.jsError.showError('',"请扫描正确的机台或工牌",'error');
					setTimeout(() => {
						this.barCode = ''
						this.focus = true;
					}, 500);
					return;
				}else if(barCode.indexOf(JT) == 0){
					const res = await this.$u.api.kst.checkFunAndBar({
						funcType: this.vuex_config.JT,
						barJT: barCode
					});
					if (res.result == "true") {
						if(res.errorMsg){
							setTimeout(() => {
								this.focus = true;
							}, 500);
							this.$refs.jsError.showError('',res.message,'error');
							return;
						}
						await this.$nextTick();
						this.barCode = '';
						this.lineCode = res.basLine.code;
						const resResult = await this.$u.api.kst.getTaskByLineCode({ lineCode: this.lineCode });

						if (resResult.result == "true") {
							this.currentRW = true;
							this.list = resResult.data;
							this.modid = this.list.length > 0 ? this.list[0]['modid'] : '';
							this.showFlag = this.list.length > 0  ? true : false
							setTimeout(() => {
								this.focus = true;
							}, 500);
						}else{
							setTimeout(() => {
								this.focus = true;
							}, 500);
							this.$refs.jsError.showError('',resResult.message,'error');
						}
					} else {
						this.$u.toast(res.message);
						setTimeout(() => {
							this.focus = true;
						}, 500);
					}
				} else if(barCode.indexOf(GP) == 0){

					const res = await this.$u.api.kst.checkFunAndBar({
						funcType:this.vuex_config.GP,
						barGP:barCode
					})
					if(res.result == "true"){

						let operatorName = res.operator.name;

						let operatorCode = res.operator.code;
						
						let bmonitor = res.operator.bmonitor;

						// 累加操作员名称或设置初始值
						if (this.operatorNames[barCode]) {
							operatorName = `${this.operatorNames[barCode]},${operatorName}`;
						}
						this.operatorNames[barCode] = operatorName;
						// this.operatorNames 去重
						this.operatorNames = [...new Set(Object.values(this.operatorNames))]
						
						const operatorNamesStr = Object.values(this.operatorNames).join(',');
						await this.$nextTick();
						this.barCode = '';
						this.list.forEach((item) => {
							// item.operator = operatorName
							item.operator = operatorNamesStr
							// 字符串 operatorCode 是否存在于字段 item.userCodes
							if (!item.userCodes.includes(operatorCode)) {
								item.showOperation = true;
							}else{
								item.showOperation = false;
							}
							item.monitor = ''
						});	
						setTimeout(() => {
							this.barCode = '';
							this.focusGP = true;
						}, 500);
						this.$forceUpdate()	
					}else{
						this.$refs.jsError.showError('', res.message, 'error');
						setTimeout(() => {
							this.barCode = '';
							this.focus = true;
						}, 500);
					}
				} 
			},
			// 扫工牌开始
			confirmSearchGP(){	
				this.focusGP = false
				this.commonSearchGP(this.barCodeGP)			
			},
			searchGP(){
				var _that = this;
				_that.focusGP = false
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: async (res) => {
						_that.barCode = res.result;
						await _that.commonSearchGP(res.result)
					},
				});
			},
			async commonSearchGP(barCode){				
				let GP = this.vuex_config.GP;
				if (barCode.indexOf(GP) == -1) {
					this.$refs.jsError.showError('',"请扫描正确的工牌",'error');
					setTimeout(() => {
						this.barCodeGP = ''
						this.focusGP = true;
					}, 500);
					return;
				} else if(barCode.indexOf(GP) == 0){

					const res = await this.$u.api.kst.checkFunAndBar({
						funcType:this.vuex_config.GP,
						barGP:barCode
					})
					if(res.result == "true"){
						let operatorName = res.operator.name;
						let bmonitor = res.operator.bmonitor;
						// 累加操作员名称或设置初始值
						// if (this.operatorNames[barCode]) {
						// 	operatorName = `${this.operatorNames[barCode]},${operatorName}`;
						// }
						// this.operatorNames[barCode] = operatorName;
						// // this.operatorNames 去重
						// this.operatorNames = [...new Set(Object.values(this.operatorNames))]
						
						// const operatorNamesStr = Object.values(this.operatorNames).join(',');
						await this.$nextTick();
						this.barCode = '';
						if(bmonitor == '1'){
							this.list.forEach((item) => {
								item.monitor = operatorName
							})
							this.barCodeGP = operatorName
							setTimeout(() => {
								this.barCode = '';
								this.focus = true;
							}, 500);
						}else{
							this.$refs.jsError.showError('', '请扫码班长工牌', 'error');	
							setTimeout(() => {
								this.barCodeGP = '';
								this.focusGP = true;
							}, 500);
						}	
						setTimeout(() => {
							this.barCode = '';
							this.focus = true;
						}, 500);
						this.$forceUpdate()	
					}else{
						this.$refs.jsError.showError('', res.message, 'error');
						setTimeout(() => {
							this.barCode = '';
							this.focus = true;
						}, 500);
					}
				} 
			},			
			// 扫工牌结束
			confirm(){
				// 获取list的id,字符串逗号分隔
				if (!this.list[0]?.operator) {
					this.$refs.jsError.showError('', '请扫码操作工', 'error');
					return;
				}	
				// if(!!this.list[0].showOperation){
				// 	if (!this.list[0]?.monitor) {
				// 		this.$refs.jsError.showError('', '请扫码班长', 'error');
				// 		return;
				// 	}
				// }
				let ids = ''
				for(let i=0;i<this.list.length;i++){
					ids += this.list[i]['id']+','
				}
				this.$u.api.kst.taskUp({
					selIds:this.list[0]['id'],
					lineCode:this.lineCode,
					operator:this.list[0]?.operator,	
					monitor:this.list[0]?.monitor
				}).then(async (res)=>{
					if(res.result=="true"){
						this.$u.toast(res.message);
						this.list[0].operator = '';
						const resResult = await this.$u.api.kst.getTaskByLineCode({ lineCode: this.lineCode });
						if (resResult.result == "true") {
							this.list = resResult.data;
							this.list.forEach((item) => {
								item.isDelFlag = false;
							});
							this.showFlag = this.list.length > 0 ? true : false;
						}
						this.$forceUpdate()
					}else{
						// this.$u.toast(res.message);
						this.$refs.jsError.showError('',res.message,'error');
					}
				})

			},
			selectSJ(){
				uni.navigateTo({
					url: "/pages/mes/shangji/bSelect?modid=" + this.modid + '&lineCode=' + this.lineCode
				});
			},
			async showCustomModal(message) {
			  this.modalMessage = message;
			  this.showModal = true;
			  // 模拟同步等待用户操作
			  return new Promise((resolve) => {
			    this.onModalClose = (result) => {
			      this.modalResult = result;
			      this.showModal = false;
			      resolve(this.modalResult);
			    };
			  });
			},
			onModalClose(result) {
			  this.$emit("update:close", result);
			},
			onErrorClose(result) {
			//   this.$emit("update:errorcClose", result);
			//   获取focus 焦点
				this.focus = result;
				setTimeout(() => {
					this.barCode = ''
					this.focus = true;
				}, 100);
			 
			},
		}
	}	
</script>

<style scoped>

	.bg-confirm {
	  background: #3e97b0;
	  color: #ffffff;
	}
	.title{
		width: 180rpx;
	}
	.text-sl{
		font-size: 60rpx;
	}
	.dictLabel{
		position: absolute;
		top: -10px;
		right: -10px;
	}
</style>